/**
* @Description: 默认请求实例
* @Author: luhan
* @Date: 2021/04/07 17:08:15
* @export {Object} axios实例
*/
import axios from 'axios';
import { requestTimeout } from '../../public/config/index.json';
import { MessageUtil } from '../utils/MessageUtil';
import { encryptParams, decryptParams, RASKEY } from '../utils/crypto';

const ENCRYPTEDINTERFACES = ['/app/', '/user/'];
const INTERFACESWITHTOKEN = ['/app/', '/user/'];

function beInculuedEncryptedInterfaces(url) {
  for (let index = 0; index < ENCRYPTEDINTERFACES.length; index += 1) {
    let item = ENCRYPTEDINTERFACES[index];
    if (url.startsWith(item)) {
      return true;
    }
  }
  return false;
}

function beInculuedInterfaceswithtoken(url) {
  for (let index = 0; index < INTERFACESWITHTOKEN.length; index += 1) {
    let item = INTERFACESWITHTOKEN[index];
    if (url.startsWith(item)) {
      return true;
    }
  }
  return false;
}
/**
* @Description: 基于axios创建的实例，进行初始化操作
* @Author: luhan
* @Date: 2021/04/08 11:40:10
* @param {Object} config 配置文件
*/
const instance = axios.create({
  showLoading: true, // 是否展示loading框，默认开启
  baseURL: `${window.location.origin}${process.env.VUE_APP_PATH}`, // 接口地址
  timeout: requestTimeout, // 超时时间
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
instance.interceptors.request.use((config) => {
  let conf = Object.create(config);
  // loading 处理
  if (conf.showLoading) {
    // TODO: 展示loading
  }
  // token
  if (beInculuedInterfaceswithtoken(conf.url)) {
    conf.headers.token = 'token';
    conf.headers.userId = '123';
  }
  // 加密
  if (beInculuedEncryptedInterfaces(conf.url)) {
    conf.headers.interceptor = RASKEY;
    conf.data.token = conf.headers.token;
    conf.data = encryptParams(conf.data);
  }
  return conf;
}, (error) => {
  MessageUtil.log(error);
  Promise.reject(error);
});

// 响应拦截器
instance.interceptors.response.use((response) => {
  MessageUtil.log(response);
  let resp = { ...response };
  const { config, data } = resp;
  if (!data || !data.headers) {
    alert('网络请求异常。错误码：01');
    return null;
  }
  // 状态码处理
  // TODO:状态码处理
  // 解密
  if (beInculuedEncryptedInterfaces(config.url)) {
    resp.data.body = decryptParams(resp.data.body);
  }
  return resp.data.body;
}, (error) => {
  MessageUtil.log(error);
  Promise.reject(error);
});

export default instance;
